﻿using System;
using System.Collections.Generic;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.DataAccess.Repositories;
using System.Data.Entity;
using Legazpi.Payroll.DataAccess.DataObjects;
using Legazpi.Payroll.DataAccess.Base;
using System.Linq;

namespace Legazpi.Payroll.BusinessLogic.Services
{
    public class SectorService : ISectorService
    {
        #region Fields

        private DbContext _dbContext;
        private ISectorRepository _sectorRepository;
        private IDatabaseFactory _dbFactory;
        #endregion

        #region ctor

        public SectorService()
            : this(new DatabaseFactory())
        {

        }

        public SectorService(IDatabaseFactory dbFactory)
        {
            if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();
        }

        private DbContext DbContext
        {
            get { return _dbContext; }
            set
            {
                _dbContext = value;
                _sectorRepository = new SectorRepository(_dbContext);
            }
        }

        #endregion

        public Sector GetById(int id)
        {
            return _sectorRepository.GetById(id);
        }

        public IEnumerable<Sector> GetAll()
        {
            return _sectorRepository.GetAll();
        }

        public IEnumerable<Sector> Get(int multiplier, int count)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Sector> GetSectorsByClientId(int clientId)
        {
            return GetAll().Where(x => x.ClientId == clientId);
        }

        public void Add(Sector sector)
        {
            _sectorRepository.Add(sector);
        }

        public void Update(Sector sector)
        {
            _sectorRepository.Update(sector);
        }

        public void Delete(int id)
        {
            var sector = GetById(id);
            if (sector != null)
                _sectorRepository.Delete(sector);
        }

        public bool Save()
        {
            string message;
            _sectorRepository.Save(out message);
            return message == "Saved";
        }
    }
}
